# SPDX-FileCopyrightText: Copyright (c) 2023-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import List

from .base import EmbeddingModel


class NIMEmbeddingModel(EmbeddingModel):
    """Embedding model using langchain-nvidia-ai-endpoints.

    This class is a wrapper for using embedding models powered by NIM (hosted in the NVIDIA API Catalog or locally).

    Args:
        embedding_model (str): The name embedding model to be used.

    Attributes:
        model: The name of the model to be called for creating embeddings.
        embedding_size: The dimensionality of the embeddings generated by the model.
    """

    engine_name = "nim"

    def __init__(self, embedding_model: str, **kwargs):
        try:
            from langchain_nvidia_ai_endpoints import NVIDIAEmbeddings  # type: ignore

            self.model = embedding_model
            self.document_embedder = NVIDIAEmbeddings(model=embedding_model, **kwargs)

        except ImportError:
            raise ImportError(
                "Could not import langchain_nvidia_ai_endpoints, please install it with "
                "`pip install langchain-nvidia-ai-endpoints`."
            )

    async def encode_async(self, documents: List[str]) -> List[List[float]]:
        """Encode a list of documents into their corresponding sentence embeddings.

        Args:
            documents (List[str]): The list of documents to be encoded.

        Returns:
            List[List[float]]: The list of sentence embeddings, where each embedding is a list of floats.
        """

        result = await self.document_embedder.aembed_documents(documents)
        return result

    def encode(self, documents: List[str]) -> List[List[float]]:
        """Encode a list of documents into their corresponding sentence embeddings.

        Args:
            documents (List[str]): The list of documents to be encoded.

        Returns:
            List[List[float]]: The list of sentence embeddings, where each embedding is a list of floats.
        """
        return self.document_embedder.embed_documents(documents)


class NVIDIAAIEndpointsEmbeddingModel(NIMEmbeddingModel):
    """A wrapper with a different name for the NIM embedding models.

    There will be a better separation in the future between local NIM and NVIDIA AI Endpoints.
    """

    engine_name = "nvidia_ai_endpoints"
